import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Button, App } from 'antd';

import { sendSms } from '@/service/base';
import { updatePhone } from '@/service/api';

const EditPhoneModal = ({ visible, onCancel, onOk }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const { message } = App.useApp();

  // 倒计时逻辑
  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
    }
    return () => clearTimeout(timer);
  }, [countdown]);

  // 发送验证码
  const sendVerificationCode = async () => {
    try {
      const mobile = form.getFieldValue('mobile');
      if (!mobile) {
        message.error('请先输入手机号');
        return;
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(mobile)) {
        message.error('请输入正确的手机号格式');
        return;
      }

      setSendingCode(true);
      
      const [res, err] = await sendSms({ mobile, code: 'update-mobile' });
      if (err) return message.error('发送验证码失败，请重试');

      message.success('验证码已发送');
      setCountdown(60); // 60秒倒计时
      
    } catch (error) {
      message.error('发送验证码失败，请重试');
    } finally {
      setSendingCode(false);
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 调用修改手机号API
      const [res, err] = await updatePhone({mobile: values.mobile, code: values.code});
      if (err) {
        message.error(err.message || '修改手机号失败，请重试');
        return;
      }
      
      if (window.OK_CODE === res?.code?.toString()) {
        message.success('手机号修改成功');
        onOk(values.mobile);
        form.resetFields();
      } else {
        message.error(res?.message || '修改手机号失败，请重试');
      }
      
    } catch (error) {
      if (error.errorFields) {
        // 表单验证错误，不需要显示消息
        return;
      }
      message.error('修改手机号失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 取消操作
  const handleCancel = () => {
    form.resetFields();
    setCountdown(0);
    onCancel();
  };

  return (
    <Modal
      title="修改手机号"
      open={visible}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
          确认修改
        </Button>,
      ]}
      destroyOnHidden={true}
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Form.Item
          label="手机号"
          name="mobile"
          rules={[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
          ]}
          style={{ marginBottom: 16 }}
        >
          <Input placeholder="请输入手机号" maxLength={11} />
        </Form.Item>

        <Form.Item
          label="验证码"
          name="code"
          rules={[
            { required: true, message: '请输入验证码' },
            { len: 6, message: '验证码为6位数字' }
          ]}
        >
          <div style={{ display: 'flex', gap: 8 }}>
            <Input placeholder="请输入6位验证码" maxLength={6} style={{ flex: 1 }} />
            <Button
              onClick={sendVerificationCode}
              loading={sendingCode}
              disabled={countdown > 0}
              style={{ minWidth: 100 }}
            >
              {countdown > 0 ? `${countdown}s后重发` : '发送验证码'}
            </Button>
          </div>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditPhoneModal;